// 依赖 npm install archiver -D
const fs = require('fs')
const path = require('path')
const archiver = require('archiver')

const homedir = __dirname
const log = console.log.bind(console, '✔ ')
const zipName = 'molv.h5'
const excludedFolders = ['node_modules', '.git'];

// 压缩dist
const addZip = () => {
  const tag = formatDateTime(new Date(), '{m}{d}{h}{i}{s}')
  // 默认在当前目录路径生成此文件 dist.zip
  const fileName = `${zipName}@${tag}.zip`
  const output = fs.createWriteStream(homedir + `/${fileName}`)
  const archive = archiver('zip', {
    // 设置压缩级别
    zlib: { level: 9 }
  })
  archive.on('error', function (err) {
    throw err
  })
  output.on('close', function () {
    log('压缩成功')
    log(`文件大小：${(archive.pointer() / 1024 / 1024).toFixed(1)}MB`)
    log(`文件路径：${homedir}/dist/${fileName}`)
    // log(`vscode://file/${homedir}/dist/${fileName}\n`)
    moveZip(fileName)
  })
  // 管道归档数据到文件
  archive.pipe(output)
  // 遍历目录并添加文件到zip，排除指定文件夹
  function globFiles(dir, excludedFolders, archive) {
    fs.readdirSync(dir).forEach(function(file) {
      const filePath = path.join(dir, file);
      const stat = fs.statSync(filePath);

      if (stat.isDirectory()) {
        // 检查文件夹是否在排除列表中
        if (!excludedFolders.includes(file)) {
          // 如果不在排除列表中，则递归处理子文件夹
          globFiles(filePath, excludedFolders, archive);
        }
      } else {
        // 如果是文件，则添加到zip中
        archive.file(filePath, { name: path.relative(__dirname, filePath) });
      }
    });
  }
  // 从当前目录开始添加文件
  globFiles(homedir, excludedFolders, archive);
  // 完成归档
  archive.finalize()
}


// 自动创建dist
const mkDist = (dirName = 'dist') => {
  // 要检查的目录路径
  const dirPath = path.join(__dirname, dirName)
  // 异步检查目录是否存在
  fs.access(dirPath, fs.constants.F_OK, (err) => {
    if (err) {
      fs.mkdir(dirPath, { recursive: true }, (mkdirErr) => {
        if (mkdirErr) {
          console.error(mkdirErr);
        } else {
          log('创建目录')
        }
      });
    }
  });
}

// 移动到dist
const moveZip = (fileName) => {
  var sourceFile = path.join(__dirname, fileName)
  var destPath = path.join(__dirname, 'dist', fileName)
  fs.rename(sourceFile, destPath, function (err) {
    if (err) throw err
    fs.stat(destPath, function (err, stats) {
      if (err) throw err
      // console.log('stats: ' + JSON.stringify(stats))
    })
  })
}

// 格式化时间
const formatDateTime = (time, format = '{y}年{m}月{d}日 星期{a} {h}:{i}:{s}') => {
  // eslint-disable-next-line no-undef
  if (arguments.length === 0 || !time) return null
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timestr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // eslint-disable-next-line standard/computed-property-even-spacing
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return timestr
}

mkDist()
addZip()
